package com.yuerlive.rainbow.module.login;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuerlive.rainbow.API;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.login.presenter.LoginContract;
import com.yuerlive.rainbow.module.login.presenter.LoginPresenter;
import com.yuerlive.rainbow.module.main.MainActivity;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.FileUploadUtil;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.ToastUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CircleImageView;
import com.yuerlive.rainbow.widget.CustomBottomSheetDialog;
import com.yuerlive.rainbow.widget.ResizeLayout;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Admin on 2017/6/2.
 */

public class CompleteInfoActivity extends BaseActivity implements LoginContract.View {
    @BindView(R.id.llParent)
    LinearLayout llParent;
    @BindView(R.id.rlResizeLayout)
    ResizeLayout rlResizeLayout;
    @BindView(R.id.commonHeader)
    RelativeLayout commonHeader;
    @BindView(R.id.ivCamera)
    CircleImageView ivCamera;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.tvGirl)
    TextView tvGirl;
    @BindView(R.id.tvBoy)
    TextView tvBoy;
    @BindView(R.id.tvNickname)
    TextView tvNickname;
    @BindView(R.id.etNickname)
    EditText etNickname;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.headerBack)
    ImageView headBack;
    private LoginContract.Presenter presenter;
    private String headUrl;
    private static final int BOY = 0;
    private int userSex;
    private BottomSheetDialog bottomSheetDialog;
    private String filename; // 图片名称
    private File outputImage;
    private Uri imageUri; // 图片路径
    private static final int REQUEST_TAKE_PHOTO = 3;
    private static final int REQUEST_CROP_PHOTO = 4;
    private HashMap<String, String> params = new HashMap<>();
    private int[] locationXY = new int[2];
    private int commentPositionY = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    //   hideLoading();
                    try {
                        Bundle resultData = msg.getData();
                        String result = resultData.getString("result");
                        JSONObject object = new JSONObject(result);
                        if (!TextUtils.isEmpty(object.getString("object").toString())) {
                            String imgName = object.getString("object").toString();
                            headUrl = imgName;
                            GlideUtil.load(CompleteInfoActivity.this, imgName, ivCamera);
                        } else {
                            ToastUtils.show("上传失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case FileUploadUtil.FAILED:
                    // hideLoading();
                    ToastUtils.show("上传失败");
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_complete_info;
    }

    @Override
    protected void initViews() {
        presenter = new LoginPresenter(this);
        setTitle("");
        tvRight.setText("跳过");
        headBack.setVisibility(View.GONE);
        setSexState(BOY);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tvSure.getLocationOnScreen(locationXY);
                commentPositionY = DeviceUtils.deviceHeight(CompleteInfoActivity.this) - (locationXY[1] + tvSure.getHeight());
            }
        }, 100);
        rlResizeLayout.setOnKeyboardShowListener(new ResizeLayout.OnkeyboardShowListener() {
            @Override
            public void onKeyboardShow(int heightDiff) {
                rlResizeLayout.setPadding(0, -(heightDiff - commentPositionY), 0, 0);
            }

            @Override
            public void onKeyboardHide() {
                rlResizeLayout.setPadding(0, 0, 0, 0);
            }
        });
    }

    private void setSexState(int sex) {
        if (sex == BOY) {
            tvGirl.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_unselected), null, null, null);
            tvBoy.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_selected_red), null, null, null);
            userSex = 0;
        } else {
            tvGirl.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_selected_red), null, null, null);
            tvBoy.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_unselected), null, null, null);
            userSex = 1;
        }

    }

    @Override
    public void showImgCode(String imgUrl) {

    }

    @Override
    public void loginResult(User user) {

    }

    @Override
    public void sendSuccess(BaseData baseData) {
        if (baseData != null && baseData.getCode() == 0) {
            showToast("完善信息成功");
            User user = UserProxy.getUser();
            user.getUserInfo().setIcon(headUrl);
            user.getUserInfo().setSex(userSex);
            user.getUserInfo().setNickname(etNickname.getText().toString());
            UserProxy.setUser(user);
            finish();
            jumpToActivity(MainActivity.class);
        }
    }

    @Override
    public void bindMobileSuccess(BaseData baseData) {

    }

    @Override
    public void showFail(String message, String api) {

    }

    @Override
    public void loginFaild(int code, String result) {

    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        super.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @OnClick({R.id.tvSure, R.id.tvBoy, R.id.tvGirl, R.id.ivCamera, R.id.tvRight})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvSure:
                if (TextUtil.isEmpty(etNickname.getText().toString())) {
                    showSnackbar(llParent, "请填写您的昵称", 0);
                    return;
                }
                if (TextUtil.isEmpty(headUrl)) {
                    showSnackbar(llParent, "请设置您的头像", 0);
                    return;
                }
                presenter.completeInfo(headUrl, etNickname.getText().toString(), userSex);
                break;
            case R.id.tvBoy:
                setSexState(0);
                break;
            case R.id.tvGirl:
                setSexState(1);
                break;
            case R.id.ivCamera:
                showOrHiddenBottomSheetDialog();
                break;
            case R.id.tvRight:
                finish();
                jumpToActivity(MainActivity.class);
                break;
        }
    }

    private void showOrHiddenBottomSheetDialog() {
        if (bottomSheetDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(this);
            View contentView = View.inflate(this, R.layout.bottom_sheet_dilaog, null);
            bottomSheetDialog = dialog.getInstance(contentView);
            contentView.findViewById(R.id.tvOpenPhoto).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvOpenPictrue).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvCancle).setOnClickListener(clickListener);
        }
        bottomSheetDialog.show();
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!checkPermissions(new String[]{Manifest.permission.CAMERA})) {
                requestPermission(new String[]{Manifest.permission.CAMERA}, 0x0001);
                return;
            }
            switch (v.getId()) {
                case R.id.tvOpenPhoto:
                    openCamera();
                    break;
                case R.id.tvOpenPictrue:
                    takeAlbum();
                    break;
            }
            if (bottomSheetDialog != null && bottomSheetDialog.isShowing()) {
                bottomSheetDialog.dismiss();
            }
        }
    };

    private void openCamera() {
        // 图片名称 时间命名
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        filename = format.format(date);
        // 创建File对象用于存储拍照的图片 SD卡根目录
        // 存储至DCIM文件夹
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        outputImage = new File(path, filename + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将File对象转换为Uri并启动照相程序
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // 照相
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // 指定图片输出地址
        startActivityForResult(intent, REQUEST_TAKE_PHOTO); // 启动照相
    }

    private void takeAlbum() {
        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        getAlbum.setType("image/*");
        startActivityForResult(getAlbum, 5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
            intent.setDataAndType(imageUri, "image/*");
            intent.putExtra("scale", true);
            // 设置宽高比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // 设置裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("return-data", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 广播刷新相册
            Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intentBc.setData(imageUri);
            this.sendBroadcast(intentBc);
            startActivityForResult(intent, REQUEST_CROP_PHOTO); // 设置裁剪参数显示图片至ImageView
        } else if (requestCode == REQUEST_CROP_PHOTO && resultCode == RESULT_OK) {

            if (data != null && data.getExtras() != null) {
                Bitmap b = (Bitmap) data.getExtras().get("data");
                if (b != null) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = new Date(System.currentTimeMillis());
                    filename = format.format(date);
                    // 创建File对象用于存储拍照的图片 SD卡根目录
                    // 存储至DCIM文件夹
                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    outputImage = new File(path, filename + ".jpg");
                    try {
                        if (outputImage.exists()) {
                            outputImage.delete();
                        }
                        outputImage.createNewFile();
                        b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(outputImage));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            uploadUserHead();
        } else if (requestCode == 5) {
            if (data != null) {
                startPhotoZoom(data.getData());
            }
        }
    }

    private void uploadUserHead() {
        params.clear();
        final Map<String, String> fileParams = new HashMap<>();
        fileParams.put("pic", outputImage.getAbsolutePath());
        User user = UserProxy.getUser();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //上传剪切后的照片
                FileUploadUtil.uploadImageFile(API.HOST + API.UPLOAD_PIC, params, fileParams, mHandler);
            }
        }).start();
    }

    private void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 4);
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }
}
